<template>
  <BasicModal v-bind="$attrs" @register="register" showFooter :title="getTitle" width="70%" @ok="handleSubmit"
    :showOkBtn="false" :okButtonProps="{ loading }">

    <div style="height: 400px;">
      <div>采购单号:{{ dataJson.orderNo }}</div>
      <div v-if="noMappingList.length > 0">
        <div>未关联物料号:{{ noMappingList.length }}</div>
        <span v-for="item in noMappingList" :key="item.mtid" style="padding-right: 5px;">
          {{ item.mtid }}
        </span>
      </div>
      <div>
        <div>订单状态 order_status:{{ orderStatus }}</div>
      </div>
      <vxe-grid ref="tableRef" v-bind="gridOptions">
        <template #toolbar_buttons>
          <Button type="primary" @click="addRowFn" size="small" v-if="is_create">添加</Button>
        </template>
        <template #mtid_slot="{ row }">
          <span style="color: red;" v-if="row.color">{{ row.mtid }}</span>
          <span v-else>{{ row.mtid }}</span>
        </template>
        <template #action="{ row }">
          <TableAction outside :actions="getActions(row)" />
        </template>
      </vxe-grid>
    </div>
    <EditFormModal @register="orderModal[0]" @success="handleSuccess"></EditFormModal>

  </BasicModal>
</template>
<script lang="ts" setup>
import EditFormModal from './EditFormModal.vue';

import { ref, computed, unref, h, toRaw, reactive } from 'vue';
import { useModal } from '@/components/Modal';

import { BasicForm, useForm } from '@/components/Form';
import { BasicTable, useTable, TableAction } from '@/components/Table';
import {
  BasicTableProps,
  VxeBasicTable,
  VxeGridInstance,
  VxeGridListeners,
  VxeTableDefines,
} from '@/components/VxeTable';

import {
  componentColumns, labelColumns, componentColumns2
} from './role.data';

import { BasicModal, useModalInner } from '@/components/Modal';
import { Form, FormItem, Input, InputNumber, DatePicker, Select, Button } from 'ant-design-vue';


import { productSave, itemNoMapping, orderItemList, orderEditRemove, orderDetail } from '@/api/heng/dkn';


import { useMessage } from "@/hooks/web/useMessage";


const emit = defineEmits(['success', 'register']);
const isUpdate = ref(true);
const { createMessage } = useMessage();
const orderModal = useModal();

const loading = ref(false);

const id = ref("")



const dataList = ref({});
const dataJson = ref({});
const itemList = ref([]);
const noMappingList = ref([]);

const tableRef = ref<VxeGridInstance>();

const gridOptions = reactive<BasicTableProps>({
  // keepSource: true,
  loading: false,
  editConfig: { trigger: 'click', mode: 'cell', showStatus: true },
  border: true,
  showOverflow: true,
  keepSource: true,
  size: 'mini',
  height: 'auto', // 'auto'
  columns: componentColumns,
  filterConfig: {
    remote: true,
  },
  exportConfig: {},
  toolbarConfig: {
    slots: {
      buttons: 'toolbar_buttons',
    },
    refresh: true,
  },
  formConfig: {
    enabled: false,
  },
  pagerConfig: {
    enabled: false,
  },
  proxyConfig: {
    enabled: false,

  },
});


const is_create = ref(false);
const getJson = ref({});
const orderStatus = ref("");

const [register, { setModalProps, closeModal }] = useModalInner(async (data) => {
  //打开弹层后的回调
  // resetFields();
  setModalProps({ confirmLoading: false });
  dataJson.value = data.record;
  // console.log("---data.record:", data.record);
  let lines = [];
  is_create.value = false;
  orderStatus.value = "";

  if (!data.record.orderCode && data.record.parameter) {
    let type = data.record.type;
    orderStatus.value = data.record.orderStatus;
    if (type == "component") {
      // loadColumn reloadColumn
      tableRef.value.reloadColumn(componentColumns2);
    } else {
      tableRef.value.reloadColumn(labelColumns);

    }

    let json = JSON.parse(data.record.parameter);
    lines = json.lines;
    dataList.value = lines;
    tableRef.value.reloadData(lines);
  } else {

    is_create.value = true;
    tableRef.value.reloadColumn(componentColumns);

    //orderItemListFn();
    orderDetailFn();
  }


});

const getTitle = computed(() => ('查看物料信息'));


//async function handleSubmit()

async function handleSubmit() {
  try {
    loading.value = true;
    const values = await validate();
    productSave(values).then(res => {
      sunccFn(res)
    }).finally(() => {
      loading.value = false;
    });


  } catch (e) {
    console.log(e)
  } finally {
    setModalProps({ confirmLoading: false });
    loading.value = false;

  }
}

function sunccFn(result) {
  if (result && result.code == 200) {
    createMessage.success(result.message);
  } else {
    createMessage.error(result.message);
  }
  closeModal()
  emit('success');
}

function cancelFn() {
  //  tableRef.value.clearValidate();
}

function orderDetailFn() {
  orderDetail(dataJson.value).then(res => {
    if (res.code == 200) {

      let json = res.data;
      getJson.value = json;
      orderStatus.value = json.header.status;

      let lines = json.lines;
      dataList.value = lines;
      tableRef.value.reloadData(lines);
    } else {
      createMessage.error(res.message);
    }
  });


}

function getMtidFn(row) {
  let c_n = "";
  if (!row.quantity) {
    c_n = "b-red";
  }
  return c_n;
}

function orderItemListFn() {
  setModalProps({ confirmLoading: true });
  gridOptions.loading = true;
  orderItemList({ inquiryCode: dataJson.value.inquiryCode }).then(res => {
    if (res.code == 200) {
      for (let k in res.data) {
        let item = res.data[k];
        if (!item.quantity) {
          item.color = 'red'
        }
      }
      itemList.value = res.data;
      tableRef.value.reloadData(res.data);

    } else {
      createMessage.error(res.message);
    }
  }).finally(() => {
    gridOptions.loading = false;

    setModalProps({ confirmLoading: false });
    itemNoMappingFn();
  });
}

function itemNoMappingFn() {
  setModalProps({ confirmLoading: true });
  gridOptions.loading = true;
  itemNoMapping({ orderNo: dataJson.value.orderNo }).then(res => {
    if (res.code == 200) {

      noMappingList.value = res.data;

    } else {
      noMappingList.value = [];
      createMessage.error(res.message);
    }
  }).finally(() => {
    gridOptions.loading = false;

    setModalProps({ confirmLoading: false });
  });
}

function getActions(record) {
  let arr = [
    {
      disable: is_create.value,

      // icon: 'clarity:note-edit-line',
      label: '修改',
      onClick: openEditOrder.bind(null, record),
    },
    {
      // icon: 'ant-design:delete-outlined',
      label: '删除',
      disable: is_create.value,
      color: 'error',
      loading: record.loading,
      popConfirm: {
        title: '是否删除？',
        placement: 'left',
        confirm: deleteOrderItem.bind(null, record),
      },
    }
  ];

  return arr;
}



function deleteOrderItem(record) {
  record.loading = true;
  record.orderCode = dataJson.value.orderCode;
  orderEditRemove(record).then(res => {
    if (res.code == 200) {
      createMessage.success(res.message);
      orderItemListFn();
    } else {
      createMessage.error(res.message);
    }
  }).finally(() => {
    record.loading = false;
  });
}

function openEditOrder(record: Recordable) {
  record.orderCode = dataJson.value.orderCode;
  orderModal[1].openModal(true, {
    isUpdate: true,
    record
  });

}

function addRowFn(record: Recordable) {
  record.orderCode = dataJson.value.orderCode;

  orderModal[1].openModal(true, {
    isUpdate: false,
    record
  });

}

function handleSuccess() {
  orderItemListFn();

}

</script>
<style lang="less">
.item-row {
  margin: 0 auto;

  //padding-left: 5%;
  .ant-form-item-label {
    flex: 0 0 28.5%;
    max-width: 28.5%;
  }
}

.lqfp-8 {
  //padding-left: 9% !important;

}

.b-red {
  background: red;
  color: gray;
}
</style>
